package com.qianniu.napi.admin.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.google.common.base.Strings;
import com.qianniu.napi.admin.entity.*;
import com.qianniu.napi.admin.entity.penum.IotypeEnum;
import com.qianniu.napi.admin.entity.penum.JftypeEnum;
import com.qianniu.napi.admin.service.ICardService;
import com.qianniu.napi.admin.service.IJifenService;
import com.qianniu.napi.admin.service.IRedisService;
import com.qianniu.napi.admin.service.IUserService;
import com.qianniu.napi.common.config.Constants;
import com.qianniu.napi.common.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.Date;

@RestController
public class CallController {

    private static final Logger logger = LoggerFactory.getLogger(BannerController.class);

    private String registUrl = "http://mp.weizhi128.com/api/user/register";

    private String smsUrl = "http://mp.weizhi128.com/api/user/sms_code";

    private String queryUrl = "http://mp.d5dadao.com/api/appapi/query";

    @Autowired
    private IRedisService redisService;
    @Autowired
    private ICardService cardService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IJifenService jifenService;

    // 短信验证功能
    @RequestMapping("/api/phone/register")
    @ResponseBody
    public JSONObject register(String name, String password, String code) {

        String time = getTime();
        logger.info("======key=" + "key_" + ObjectUtil.getAppid());
        String key = Constants.PHONE_MAP.get("key_" + ObjectUtil.getAppid());
        logger.info("======key=" + key);
        if (Strings.isNullOrEmpty(password)) {
            password = ObjectUtil.randomStrings(8, 1).get(0);
        }

        String agentId = Constants.PHONE_MAP.get("agentId_" + ObjectUtil.getAppid());
        String params = "agent_id=" + agentId + "&code=" + code + "&name=" + name + "&password=" + password;

        String rkey = "phone_register_" + ObjectUtil.getAppid();
        String rkeytime = "phone_register_" + ObjectUtil.getAppid() + "_" + time;
        String token = EncryptUtil.md5(params + time + key);
//        String token = redisService.get(rkey);
//        time = redisService.get(rkeytime);
        if (Strings.isNullOrEmpty(token)) {
            token = EncryptUtil.md5(params + time + key);
//            redisService.set(rkey, token, 59, TimeUnit.MINUTES);
//            redisService.set(rkeytime, time, 59, TimeUnit.MINUTES);
        }

        logger.info("======time=" + time);
        logger.info("======key=" + key);
        logger.info("======params=" + params);
        logger.info("======rkey=" + rkey);
        logger.info("======rkeytime=" + rkeytime);
        logger.info("======token=" + token);

        params += "&time=" + time;
        params += "&token=" + token;

        logger.info("==========request url=" + registUrl + "?" + params);
        String result = HttpUtil.sendGet(registUrl, params);

        JSONObject json = JSON.parseObject(result);
        if (json.getInteger("code") == 1 || json.getInteger("code") == -2) {
            User user = new User();
            user.setId(ObjectUtil.getUid());
            user.setHasCallfunc(1);
            user.setCallpwd(password);
            user.setPhone(name);
            user.setModifytime(new Date());
            user.updateById();
            redisService.delUser();
        }

        return json;
    }

    // 短信验证功能
    @RequestMapping("/api/phone/sms")
    @ResponseBody
    public JSONObject sms(String mobile) {

        String time = getTime();
        String agentId = Constants.PHONE_MAP.get("agentId_" + ObjectUtil.getAppid());
        String key = Constants.PHONE_MAP.get("key_" + ObjectUtil.getAppid());

        String params = "agent_id=" + agentId + "&mobile=" + mobile;

        String rkey = "phone_sms_" + ObjectUtil.getAppid();
        String token = EncryptUtil.md5(params + time + key);
//        String token = redisService.get(rkey);

        if (Strings.isNullOrEmpty(token)) {
            token = EncryptUtil.md5(params + time + key);
//            redisService.set(rkey, token, 59, TimeUnit.MINUTES);
        }

        params += "&time=" + time;
        params += "&token=" + token;

        logger.info("==========request url=" + smsUrl + "?" + params);
        String result = HttpUtil.sendGet(smsUrl, params);
        JSONObject json = JSON.parseObject(result);


        return json;
    }

    //    @RequestMapping("/api/phone/recharge")
//    @ResponseBody
    private JSONObject recharge(String mobile, String card_number, String card_password, Integer cztype) {
        logger.info("============================================================come to recharge");
        logger.info("====================mobile="+mobile);
        logger.info("====================card_number="+card_number);
        logger.info("====================card_password="+card_password);

        String time = getTime();
        String agentId = Constants.PHONE_MAP.get("agentId_" + ObjectUtil.getAppid());
        String key = Constants.PHONE_MAP.get("key_" + ObjectUtil.getAppid());

        String params = "act=recharge_card" + "&agent_id=" + agentId + "&card_number=" + card_number + "&card_password=" + card_password + "&mobile=" + mobile;
        String rkey = "phone_recharge_" + ObjectUtil.getAppid();
        String token = EncryptUtil.md5(params + time + key);
//        String token = redisService.get(rkey);
        if (Strings.isNullOrEmpty(token)) {
            token = EncryptUtil.md5(params + time + key);
//            redisService.set(rkey, token, 59, TimeUnit.MINUTES);
        }

        params += "&time=" + time;
        params += "&token=" + token;

        logger.info("==========request url=" + registUrl + "?" + params);
        String result = HttpUtil.sendGet(queryUrl, params);
        logger.info("==========request result=" + result);
        JSONObject json = new JSONObject();

        try {

            if (!Strings.isNullOrEmpty(result) && result.indexOf("充值成功") > 0) {
                Card card = new Card();

                card.setCardno(card_number);
                card.setIsUsed(1);
                card.setUseby(ObjectUtil.getUid());
                card.setUsefor(cztype);
                card.setPwd(card_password);
                card.setEnddate(DateUtil.toDateString(DateUtil.addDay(new Date(), 365), "yyyy-MM-dd"));//电话卡默认一年有效期
                cardService.update(card, new EntityWrapper<Card>().eq("cardno", card_number));

                json.put("code", 0);
            } else {
                if (result.indexOf("电话卡密码错误") > 0) {
                    json.put("code", 5);
                    json.put("msg", "电话卡密码错误");
                } else {
                    try {
                        json = JSON.parseObject(result);
                    } catch (Exception e) {
                        logger.error("==========request url=" + registUrl + "?" + params);
                        json = new JSONObject();
                        json.put("code", 5);
                        json.put("msg", "电话卡密码错误");
                    }
                }
                json = JSON.parseObject(result);
                return json;
            }
        } catch (Exception e) {
            logger.error("======recharge error", e);
            json.put("code", 5);
        }
        return json;
    }

    // 短信验证功能
    @RequestMapping("/api/phone/balance")
    @ResponseBody
    public JSONObject balance(String mobile) {
        String time = getTime();
        String agentId = Constants.PHONE_MAP.get("agentId_" + ObjectUtil.getAppid());
        String key = Constants.PHONE_MAP.get("key_" + ObjectUtil.getAppid());

        String params = "act=balance" + "&agent_id=" + agentId + "&mobile=" + mobile;

        String rkey = "phone_balance_" + ObjectUtil.getAppid();
        String token = EncryptUtil.md5(params + time + key);
        if (Strings.isNullOrEmpty(token)) {
            token = EncryptUtil.md5(params + time + key);
//            redisService.set(rkey, token, 59, TimeUnit.MINUTES);
        }

        logger.info("======time=" + time);
        logger.info("======key=" + key);
        logger.info("======params=" + params);
        logger.info("======rkey=" + rkey);
        logger.info("======token=" + token);

        params += "&time=" + time;
        params += "&token=" + token;

        logger.info("==========request url=" + registUrl + "?" + params);
        String result = HttpUtil.sendGet(queryUrl, params);
        JSONObject json = JSON.parseObject(result);

        return json;
    }

    // 短信验证功能
    @RequestMapping("/api/phone/call")
    @ResponseBody
    public JSONObject call(String mobile, String tmobile) {

        String time = getTime();
        String agentId = Constants.PHONE_MAP.get("agentId_" + ObjectUtil.getAppid());
        String key = Constants.PHONE_MAP.get("key_" + ObjectUtil.getAppid());

        String params = "act=call" + "&agent_id=" + agentId + "&mobile=" + mobile + "&target_mobile=" + tmobile;
        logger.info("======params=" + params);

        String rkey = "phone_call_" + ObjectUtil.getAppid();
        String token = EncryptUtil.md5(params + time + key);
//        String token = redisService.get(rkey);
        if (Strings.isNullOrEmpty(token)) {
            token = EncryptUtil.md5(params + time + key);
//            redisService.set(rkey, token, 59, TimeUnit.MINUTES);
        }
        ;
        logger.info("======time=" + time);
        logger.info("======key=" + key);
        logger.info("======params=" + params);
        logger.info("======rkey=" + rkey);
        params += "&time=" + time;
        params += "&token=" + token;

        logger.info("==========request url=" + registUrl + "?" + params);
        String result = HttpUtil.sendGet(queryUrl, params);
        JSONObject json = JSON.parseObject(result);


        return json;
    }

    // 充值
    @RequestMapping("/api/card/bind")
    @ResponseBody
    public JSONObject cardbind(String cardno, String cardpwd, String smscode, int cztype) {
        logger.info("============================card/bind start cardno=%s cardpwd=%s cztype=%s",cardno,cardpwd,cztype);

        JSONObject jinfo = new JSONObject();
        if (Strings.isNullOrEmpty(cardno) || Strings.isNullOrEmpty(cardpwd)) {
            jinfo.put("code", 4);
            jinfo.put("msg", "参数不能为空");
            return jinfo;
        }
        if (cardpwd.length() == 0) {
            jinfo.put("code", 4);
            jinfo.put("msg", "密码填写有误");
            return jinfo;
        }

        long mid = ObjectUtil.getMid();
        long mpid = ObjectUtil.getMpid();

//        Lipin lipin = new Lipin();
//        lipin.setMid(mid);
//        lipin.setUid(uid);
//        lipin.setMpid(mpid);
//        lipin.setCardno(cardno);
//        lipin.setCardpwd(cardpwd);
//        lipin.setCztype(cztype);
//        lipin.setCreatetime(new Date());
//        // 1、验证卡源数据正确性
//        int cout = lipinService.selectCount(new EntityWrapper<Lipin>().eq("cardno",cardno));
//        if(cout>0){
//            jinfo.put("code",1);
//            jinfo.put("msg","该卡已被绑定使用");
//            return jinfo;
//        }
//
//        // 2、记录卡
//        lipin.insert();

        // 1、验证卡源数据正确性
        Card card = cardService.selectOne(new EntityWrapper<Card>().eq("cardno", cardno));
        if (card == null) {
            jinfo.put("code", 1);
            jinfo.put("msg", "非法卡不支持绑定");
            return jinfo;
        } else if (card.getIsUsed() == 1 || card.getIsOutdate() == 1) {
            jinfo.put("code", 1);
            jinfo.put("msg", "该卡已被使用或过期");
            return jinfo;
        }
        logger.info("==============cardpwd="+cardpwd);
        logger.info("==============card="+JSON.toJSONString(card));
        if (card.getPwd() != null && !card.getPwd().equals(cardpwd)) {
            jinfo.put("code", 1);
            jinfo.put("msg", "密码不正确");
            return jinfo;
        }

        // 2、记录卡
        if(cardno.length()==14&&ObjectUtil.getMpid().intValue()==52)cztype=1;
        else cztype=2;
        logger.info("============================cztype="+cztype);

        if (cztype == 1) {
            // 3、电话卡冲话费

            User user = userService.selectOne(new EntityWrapper<User>().setSqlSelect("id,phone").eq("id", ObjectUtil.getUid()));
            return recharge(user.getPhone(), cardno, cardpwd, cztype);

        } else if (cztype == 2) {
            logger.info("============================card/bind jifen");
            // 3、冲积分
            JifenFlow jf = new JifenFlow();

            // *******  待更新  *******
            jf.setNum(card.getAmount());
            jf.setSn(StringUtil.getSnNo("J"));// 抵扣积分时 = 订单号
            jf.setIotype(IotypeEnum.input.getVal());//积分消费
            jf.setJftype(JftypeEnum.recharge.getVal());//积分消费
            jf.setCreatetime(new Date());
            jf.setUid(ObjectUtil.getUid());
            jf.setMid(mid);
            jf.setMpid(mpid);
            jf.setRemark("绑定礼品卡兑换积分");
            jf.setIsConfirm(1);
            jf.setState(1);
            jf.insert();

            boolean flag = false;
            Jifen jifen = jifenService.selectOne(new EntityWrapper<Jifen>().eq("uid", ObjectUtil.getUid()));
            while (flag != true) {

                if (jifen == null) jifen = jifenService.initJifen();
                Jifen jfen = new Jifen();
                jfen.setVersion(jifen.getVersion() + 1);
                jfen.setTotal(jifen.getTotal().add(new BigDecimal(100)));
                jfen.setModifytime(new Date());
                jfen.setId(jifen.getId());

                flag = jifenService.update(jfen, new EntityWrapper<Jifen>().eq("id", jifen.getId()).eq("version", jifen.getVersion()));
                if (!flag) jifen = jifenService.selectOne(new EntityWrapper<Jifen>().eq("uid", ObjectUtil.getUid()));
            }

            card.setIsUsed(1);
            card.setUseby(ObjectUtil.getUid());
            card.setUsefor(cztype);
            if (card.getPwd() == null) card.setPwd(cardpwd);
            if (card.getExpire() == null) DateUtil.addDay(new Date(), card.getExpire());
            card.setEnddate(DateUtil.toDateString(DateUtil.addDay(new Date(), card.getExpire()), "yyyy-MM-dd"));
            card.updateById();

            jinfo.put("code", 0);
        }

        return jinfo;
    }

    // 充值
    @RequestMapping("/test/card/test")
    @ResponseBody
    public Jinfo test() {
        Jinfo jinfo = new Jinfo();
        int m = 0;
        int a = 100 / m;
        return jinfo;
    }

    private String getTime() {
        String time = Long.valueOf(new Date().getTime()).toString();
        time = time.substring(0, time.length() - 3);
        return time;
    }

    public static void main(String[] args) {

        String time = Long.valueOf(new Date().getTime()).toString();
        time = time.substring(0, time.length() - 3);
        String key = "lzyOEMsys963852741";
        String params = "act=call&agent_id=6811&mobile=18810370168&target_mobile=15313301959";

        String token = EncryptUtil.md5(params + time + key);
        params += "&time=" + time;
        params += "&token=" + token;

        String queryUrl = "http://mp.d5dadao.com/api/appapi/query";

        String url = queryUrl + params;
        logger.info("===========url=" + url);
        logger.info("===========token=" + token);
        logger.info("===========time=" + time);

        String result = HttpUtil.sendGet(queryUrl, params);
        System.out.println("============result=" + result);


    }

}
